(function(angular) {
  'use strict';
  angular
    .module('fs.menu', ['ui.bootstrap', 'menu/menuNav.html', 'menu/menuTemplate.html', 'menu/menuItemsTemplate.html'])
    .directive('fsNav', [
      '$timeout',
      function($timeout) {
        var controller = [
          '$rootScope',
          '$scope',
          '$element',
          '$attrs',
          '$transclude',
          'storageService',
          'SYS_PARAMS',
          function($rootScope, $scope, $element, $attrs, $transclude, storageService, SYS_PARAMS) {
            var ctrl = this,
              watcher,
              watchers = [];
            ctrl.navigationCache = ctrl.navigationCache || {};
            $scope.$on('$destroy', function() {
              while (watchers.length) {
                (watchers.shift() || angular.noop)();
              }
            });
            watcher = $rootScope.$watch(
              'pageId',
              function(pageId) {
                var menus, action, missActions, hasMenu, menuKeyPrefix;
                if (
                  !pageId ||
                  pageId == 'poi.home' ||
                  pageId == 'poi.dashboard.panels' ||
                  pageId == 'poi.workflow.wfTxn.list' ||
                  pageId == 'poi.notification.view' ||
                  pageId.indexOf('poi.error.') == 0
                ) {
                  ctrl.navs = [];
                  return;
                }
                ctrl.currentStateUrl = pageId;
                if (pageId.indexOf('poi.menu.submenu') == 0) {
                  if ($scope.$stateParams.params && $scope.$stateParams.params.displayName) {
                    ctrl.navs = [$scope.$stateParams.params];
                  }
                  return;
                }
                menus = storageService.getMenuConfigInfo();
                if (ctrl.navigationCache[$rootScope.pageId]) {
                  ctrl.navs = ctrl.navigationCache[$rootScope.pageId];
                } else {
                  ctrl.navs = [];
                  ctrl.currentStateUrl = ctrl.currentStateUrl.split('.');
                  ctrl.currentStateUrl.shift();
                  action = ctrl.currentStateUrl.pop();
                  ctrl.currentStateUrl = ctrl.currentStateUrl.join('/');
                  buildMenuNav(ctrl.currentStateUrl, action, menus, ctrl.navs);

                  // hasMenu = ctrl.navs && ctrl.navs.length > 0;
                  // ctrl.currentStateUrl = ctrl.currentStateUrl.split('/');
                  // while (!hasMenu) {
                  //   if (!ctrl.currentStateUrl || ctrl.currentStateUrl.length == 0) {
                  //     break;
                  //   }
                  //   if (missActions) {
                  //     missActions.unshift(ctrl.currentStateUrl.pop().toLowerCase());
                  //   } else {
                  //     missActions = [];
                  //     missActions.push(ctrl.currentStateUrl.pop().toLowerCase());
                  //   }
                  //   ctrl.currentStateUrl = ctrl.currentStateUrl.join('/');
                  //   buildMenuNav(ctrl.currentStateUrl, '', menus, ctrl.navs);
                  //   hasMenu = ctrl.navs && ctrl.navs.length > 0;
                  //   ctrl.currentStateUrl = ctrl.currentStateUrl.split('/');
                  // }
                  // if (missActions && missActions.length > 0) {
                  //   menuKeyPrefix = ctrl.navs.length > 0 ? ctrl.navs[0] : 'title.nav.unkonw';
                  //   ctrl.navs.unshift({
                  //     displayName: menuKeyPrefix + '.' + missActions.join('.')
                  //   });
                  // }

                  // if (ctrl.navs.length > 0 && SYS_PARAMS.NAVIGATION_ACTIONS[action.toUpperCase()]) {
                  //   ctrl.navs.unshift({
                  //     displayName: SYS_PARAMS.NAVIGATION_ACTIONS[action.toUpperCase()]
                  //   });
                  // }

                  ctrl.navigationCache[$rootScope.pageId] = ctrl.navs;
                }
              },
              true
            );
            watchers.push(watcher);

            function buildMenuNav(url, action, menuItems, navs) {
              var i = 0,
                menuConfig;
              for (i = 0; i < menuItems.length; i++) {
                menuConfig = menuItems[i];
                if (menuConfig.actionName) {
                  if ((action && menuConfig.actionName == '/' + url + '/' + action) || (action && menuConfig.displayName == url + '.' + action)) {
                    navs.push(menuConfig);
                    return;
                  }
                }
                if (menuConfig.subMenuItems) {
                  buildMenuNav(url, action, menuConfig.subMenuItems, navs);
                  if (ctrl.navs && ctrl.navs.length > 0) {
                    navs.unshift(menuConfig);
                    return;
                  }
                }
              }
            }
          }
        ];
        return {
          restrict: 'EA',
          replace: true,
          controller: controller,
          controllerAs: 'fsNavController',
          link: function($scope, $element, $attr, ctrl, $transclude) {},
          templateUrl: function(element, attrs) {
            return attrs.templateUrl || 'menu/menuNav.html';
          }
        };
      }
    ])
    //<fs-menu ng-model="vm.menus"><fs-menu>
    .directive('fsMenu', [
      '$timeout',
      'storageService',
      'StorageConstants',
      function($timeout, storageService, StorageConstants) {
        var controller = ['$scope', '$element', '$attrs', '$transclude', function($scope, $element, $attrs, $transclude) {}];
        return {
          restrict: 'EA',
          replace: true,
          required: 'uibDropdown',
          controller: controller,
          link: function($scope, $element, $attrs, dropdownCtrl, $transclude) {
            var watcher;
            $scope.$on('$destroy', function() {
              watcher();
            });
            watcher = $scope.$watch($attrs.ngModel, function(newValue, oldValue) {
              $scope.fsMenu = newValue;
              angular.forEach($scope.fsMenu, function(value, key) {
                $scope.fsMenu[key].state = value.actionName ? value.actionName.split('/').join('.') : value.actionName;
              });
            });
            $scope.clickMenu = function($event, menu) {
              $scope.currentMenu = menu;
              storageService.removeItemFromSession(StorageConstants.SEARCH_CRITERIA_STORAGE_KEY);
              if (
                menu.subMenuItems &&
                menu.displayName != 'menu.pi.creditExposure' &&
                menu.displayName != 'menu.pi.query.piCustDocList' &&
                menu.displayName != 'menu.pi.creditMemo' &&
                menu.displayName != 'menu.pi.payment' &&
                menu.displayName != 'nux.menu.pi.query.piload' &&
                menu.displayName != 'menu.workflow.processingQueue' &&
                menu.displayName != 'menu.dashboard.panels' &&
                menu.displayName != 'menu.pi.query.pendingApprovalList1'
              ) {
                $scope.go('poi.menu.submenu', menu);
              } else if (menu.actionName) {
                menu.state = menu.actionName
                  .split('/')
                  .join('.')
                  .replace(/^[.]/, '')
                  .replace(/[.]$/, '');
                menu.params = angular.fromJson(menu.href);
                $scope.go(menu.state, menu.params);
              }
            };
            $scope.isCurrentMenu = function(menu) {
              if (menu.actionName) {
                return (
                  $scope.pageId ==
                  'poi.' +
                    (menu.actionName
                      ? menu.actionName
                          .split('/')
                          .join('.')
                          .replace(/^[.]/, '')
                          .replace(/[.]$/, '')
                      : '')
                );
              } else {
                return false;
              }
            };
            $scope.isCurrent = function(menu, items) {
              var i,
                f = false,
                currentStateName = $scope.$state && $scope.$state.current ? $scope.$state.current.name.split('_').join('.') : '';
              if ($scope.currentMenu == menu) {
                return true;
              } else if (menu && $scope.pageId == 'poi.menu.submenu.' + menu.displayName) {
                return true;
              } else if (menu && menu.actionName) {
                return (
                  $scope.pageId ==
                  'poi.' +
                    (menu.actionName
                      ? menu.actionName
                          .split('/')
                          .join('.')
                          .replace(/^[.]/, '')
                          .replace(/[.]$/, '')
                      : '')
                );
              }
              if (currentStateName && currentStateName.length > 0 && items && items.length > 0) {
                for (i = 0; i < items.length; i++) {
                  if (items[i].state && items[i].state.length > 0 && currentStateName.indexOf(items[i].state) >= 0) {
                    f = true;
                    break;
                  } else if (items[i].subMenuItems) {
                    f = $scope.isCurrent(items[i].subMenuItems);
                  }
                }
              }
              return f;
            };
          },
          templateUrl: function(element, attrs) {
            return attrs.templateUrl || 'menu/menuTemplate.html';
          }
        };
      }
    ])
    //<fs-menu-items ng-model="items"><fs-menu-items>
    .directive('fsMenuItems', [
      '$timeout',
      function($timeout) {
        var controller = ['$rootScope', '$scope', '$element', '$attrs', '$transclude', function($rootScope, $scope, $element, $attrs, $transclude) {}];
        return {
          restrict: 'EA',
          replace: true,
          required: '^^?uibDropdown',
          controller: controller,
          controllerAs: 'vm',
          scope: {
            fsMenu: '<ngModel',
            isOpen: '<'
          },
          link: function($scope, $element, $attr, dropdownCtrl, $transclude) {
            var watchers = [];
            $scope.$on('$destroy', function() {
              while (watchers.length) {
                (watchers.shift() || angular.noop)();
              }
            });
            angular.forEach($scope.fsMenu, function(value, key) {
              $scope.fsMenu[key].state = value.actionName
                ? value.actionName
                    .split('/')
                    .join('.')
                    .replace(/^[.]/, '')
                    .replace(/[.]$/, '')
                : '';
            });
            $scope.open = function(item) {
              if (!$scope.isOpen) {
                item.open = false;
              }
              return item.open;
            };
            $scope.clickMenu = function($event, item) {
              if (item.state) {
                $scope.go('poi.' + item.state, angular.fromJson(item.href));
              }
            };
          },
          templateUrl: function(element, attrs) {
            return attrs.templateUrl || 'menu/menuItemsTemplate.html';
          }
        };
      }
    ]);

  angular.module('menu/menuNav.html', []).run([
    '$templateCache',
    function($templateCache) {
      $templateCache.put(
        'menu/menuNav.html',
        '' +
          '<div class="navbar" ng-if="fsNavController.navs && fsNavController.navs.length > 0"><ol class="breadcrumb fs-nav" ng-if="$state.current.name">' +
          '    <li class="active" ng-repeat="navItem in fsNavController.navs">' +
          '        <a href="#" ng-class="{\'sub\': fsNavController.navs.length > 1}" ng-click="clickMenu($event, navItem)" ng-if="(navItem.actionName || navItem.subMenuItems) && fsNavController.navs.length != $index + 1">\n' +
          '            <span ng-class="{\'icon icon-local\':$index == 0 && fsNavController.navs.length > 1}"></span><span>{{navItem.displayName|translate}}</span>\n' +
          '        </a>\n' +
          '        <span ng-class="{\'top\': fsNavController.navs.length == 1}" ng-if="(!navItem.actionName && !navItem.subMenuItems) || fsNavController.navs.length == $index + 1">\n' +
          '            <span ng-class="{\'icon icon-local\':$index == 0 && fsNavController.navs.length > 1}"></span><span>{{navItem.displayName|translate}}</span>\n' +
          '        </span>\n' +
          '    </li>\n' +
          '</ol></div>\n'
      );
    }
  ]);
  angular.module('menu/menuTemplate.html', []).run([
    '$templateCache',
    function($templateCache) {
      $templateCache.put(
        'menu/menuTemplate.html',
        '' +
          '<ul class="nav navbar-nav">' +
          '    <li class="top-menu" ng-class="{\'current\':isCurrent(menu, menu.subMenuItems)}" uib-dropdown role="menu" is-open="menu.isOpen" ng-repeat="menu in fsMenu track by $index">' +
          '        <a href="#" ng-click="clickMenu($event, menu)">' +
          '            <div class="media">' +
          '                <div class="media-left media-middle">' +
          '        	           <span class="icon" ng-class="{\'icon-{{menu.icon}}\': menu.icon}"></span>' +
          '                </div>' +
          '                <div class="media-body media-middle">' +
          '                    <span>{{menu.displayName|translate}}</span>' +
          '                </div>' +
          '            </div>' +
          '        </a>\n' +
          '    </li>\n' +
          '</ul>\n'
      );
    }
  ]);
  angular.module('menu/menuItemsTemplate.html', []).run([
    '$templateCache',
    function($templateCache) {
      $templateCache.put(
        'menu/menuItemsTemplate.html',
        '' +
          '<ul class="animated fadeInUp" uib-dropdown-menu role="menu">' +
          '    <li class="divider" ng-if="!!item.separator"></li>' +
          '    <li role="menuItem" ng-repeat="item in fsMenu track by $index" ng-class="{\'dropdown-submenu\':!item.actionName, \'open\':open(item)}" ng-if="!item.separator">' +
          '          <a href="#" ng-click="clickMenu($event, item)">' +
          '              <span>{{item.displayName|translate}}</span>' +
          '          </a>\n' +
          '          <div fs-menu-items ng-if="item.subMenuItems" ng-model="item.subMenuItems" is-open="menu.isOpen"></div>\n' +
          '    </li>\n' +
          '</ul>\n'
      );
    }
  ]);
})(angular);
